package edu.vt.ece_3574.amber_alert.location;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

import com.google.android.maps.GeoPoint;

import edu.vt.ece_3574.amber_alert.database.DatabaseHandler;

public class C2DMMessageReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.w("C2DM", "Message Receiver called");
		if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
			Log.w("C2DM", "Received message");
			final String payload = intent.getStringExtra("arg");
			Log.d("C2DM", "dmControl: payload = " + payload);

			if (payload.contains("AmberAlertLocate")) {
				String[] payloadParts = payload.split(":");
				String accountName = payloadParts[1];
				String caller = payloadParts[2];
				
				LocationManager locationManager = LocationManagerHandler.getLocationManager();
				Location lastLocation = locationManager.getLastKnownLocation("gps");
				double latitude = lastLocation.getLatitude();
				double longitude = lastLocation.getLongitude();
				GeoPoint locationPoint = new GeoPoint((int) (longitude * 1E6), (int) (latitude * 1E6));
				
				DatabaseHandler.get().getAccountFromServerByName(accountName).setLocation(locationPoint);
				DatabaseHandler.get().notifyAccountThisLocationIsUpdated(caller);
			}
			else if (payload.contains("AmberAlertAccountLocated")) {
				PendingLocateAccount.get().located();
			}
		}
	}
}